package com.platform.framework.util.sign;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.crypto.SecureUtil;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.platform.framework.entity.pub.TradeFlow;
import com.platform.framework.vo.transfer.TransportLayer;


/**
 * 签名工具
 * @author ly-liugaoyang
 *
 */
@SuppressWarnings("unchecked")
public class SignUtil {
	
	private static Logger logger = Logger.getLogger(SignUtil.class);
	
	/**
	 * 微信支付回调监听器
	 * @param map
	 * @author ly-liuxianliang
	 *
	 */
	public static String getSign(Map<String, Object> map,TransportLayer transportLayer) {
		logger.info("------------- getSign start -------------");
		logger.info("key in vo is : " + transportLayer.getWxKey());
		ArrayList<String> list = new ArrayList<String>();
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			if (entry.getValue() != "") {
				list.add(entry.getKey() + "=" + entry.getValue() + "&");
			}
		}
		int size = list.size();
		String[] arrayToSort = list.toArray(new String[size]);
		Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < size; i++) {
			sb.append(arrayToSort[i]);
		}
		String result = sb.toString();
		result += "key=" + transportLayer.getWxKey();
		logger.info("签名参数排列：" + result);
		result = MD5.MD5Encode(result).toUpperCase();
		logger.info("原生签名加密完成，sign is :" + result);
		logger.info("------------- getSign end -------------");
		return result;
	}
	
	/**
	 * 微信回调验签
	 * @param xml
	 * @return
	 */
	public static boolean checkVerify(String xml,TransportLayer transportLayer) {
		try {
//			String resultCode = XmlUtil.getParam(xml, "out_trade_no");
			logger.info("start check Sign from Wx......");
			Document document = DocumentHelper.parseText(xml);
			Element root = document.getRootElement();
			List<Element> elements = root.elements();
			String sign = "";
			Map<String, Object> map = new HashMap<String, Object>();
			for( Element e : elements ) {
				if( "sign".equals(e.getName()) ) {
					logger.info("his sign is : " + e.getTextTrim());
					sign = e.getTextTrim();
				} else if("tradeFlowId".equals(e.getName())){ // 跳过tradeFlowId 不然验签会报错
					continue;
				} else {
					logger.info("微信回调验签参数：" + e.getName() + "=" + e.getTextTrim());
					map.put(e.getName(), e.getTextTrim());
				}
			}
			String mysign = getSign(map,transportLayer);
			logger.info("my sign is : " + mysign);
			if( mysign.equals(sign) ) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	
	public static String MD5Sign (TradeFlow tradeFlow) {
		String tradeFlowSign = tradeFlow.getRemark()+ tradeFlow.getOrderNo() + tradeFlow.getSubAccountId() + tradeFlow.getTotalAmount();
		return MD5.MD5Encode(tradeFlowSign);
	}
	
	public static void main(String[] args) {
		TradeFlow tradeFlow = new TradeFlow();
		tradeFlow.setRemark("huodong_discount_gift");
		tradeFlow.setOrderNo("0003391477289619");
		tradeFlow.setSubAccountId("H2901");
		tradeFlow.setTotalAmount("0.10");
		String md5Sign = MD5Sign(tradeFlow);
		System.out.println(md5Sign);
	}
}
